<template>
  <Swiper
    v-if="listComp.length > 0"
    @swiper="onSwiper"
    class="my-swiper-container"
    :modules="[SwiperAutoplay, SwiperEffectCreative]"
    slides-per-view="auto"
    :loop="true"
    :autoplay="{ delay: delay, disableOnInteraction: false }"
    :space-between="24"
    @mouseover="onMouseOver"
    @mouseout="onMouseOut"
  >
    <SwiperSlide v-for="(picSrc, i) in listComp" :key="`${picSrc}-${i}}`">
      <NuxtImg
        class="w-[190px] h-[64px]"
        preload
        loading="lazy"
        :src="picSrc"
      />
    </SwiperSlide>
  </Swiper>
</template>

<script setup lang="ts">
import type { Swiper } from "swiper/types";
const props = withDefaults(
  defineProps<{
    /**
     * 循环展示的logo图片地址
     */
    logoPicSrcArr?: string[];
    /**
     * 滚动一次之后多久再开始滚动. 单位: 毫秒. 默认: 3000
     */
    delay: number;
    /**
     * 延迟启动swiper轮播的延迟时间。单位:毫秒. 默认: 0 表示不延迟启动.
     */
    delayStart?: number;
  }>(),
  {
    logoPicSrcArr: () => [],
    delay: 3000,
    delayStart: 0,
  }
);

const { logoPicSrcArr, delayStart } = toRefs(props);
const listComp = computed(() => {
  const arr = [];
  const tmpArr = logoPicSrcArr.value;
  // 将logoPicSrcArr数据复制3倍。原因: 数据数据太少，swiper 只会循环一遍，原因不明
  if (tmpArr && tmpArr.length > 0) {
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < tmpArr.length; j++) {
        arr.push(tmpArr[j]);
      }
    }
  }
  return arr;
});
let timeoutFlag: number | null = null;
let swiper: Swiper | null = null;
function onSwiper(_swiper: Swiper) {
  swiper = _swiper;
  doStartLoop();
}

function doStartLoop() {
  if (process.client) {
    doClearTimeout();
    if (delayStart.value > 0) {
      timeoutFlag = window.setTimeout(() => {
        swiper?.autoplay.start();
      }, delayStart.value);
    } else {
      swiper?.autoplay.start();
    }
  }
}

function doStopLoop() {
  doClearTimeout();
  swiper?.autoplay.stop();
}

function doClearTimeout() {
  if (process.client && timeoutFlag) {
    window.clearTimeout(timeoutFlag);
  }
}

function onMouseOver() {
  doStopLoop();
}
function onMouseOut() {
  doStartLoop();
}

function onWindowResize() {
  doStopLoop();
  doStartLoop();
}
function listenWindowResize() {
  process.client && window.addEventListener("resize", onWindowResize);
}
onMounted(() => {
  listenWindowResize();
});
onBeforeUnmount(() => {
  process.client && window.removeEventListener("resize", onWindowResize);
});
</script>

<style scoped lang="scss">
.my-swiper-container {
  max-width: 1280px !important;
  .swiper-slide {
    width: auto !important;
  }
}
</style>
